/**
 * 
 */
package pay.util;

import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

/**
 * @author suanp
 */
public class WxUtils {

	/**
	 * 获取参数签名
	 * 
	 * @param parameters
	 * @param charSet
	 * @return
	 */
	public static String getSign(SortedMap<String, Object> parameters, String apiKey, String charsetName)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		Iterator<String> itr = parameters.keySet().iterator();
		while (itr.hasNext()) {
			String paramKey = itr.next();
			Object val = parameters.get(paramKey);
			if (!StringUtils.equalsIgnoreCase(paramKey, "sign") && !StringUtils.equals(paramKey, "key")
					&& val != null) {
				sb.append(paramKey + "=" + val + "&");
			}
		}
		sb.append("key=" + apiKey);
		return DigestUtils.md5Hex(sb.toString().getBytes(charsetName)).toUpperCase();
	}

	/**
	 * 转换请求xml
	 * 
	 * @param parameters
	 * @return
	 */
	public static String getReqXml(SortedMap<String, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		for (Map.Entry<String, Object> entry : parameters.entrySet()) {
			String k = (String) entry.getKey();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + entry.getValue() + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + entry.getValue() + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

}
